<template>
  <div class="permissions-wrap">
    <el-row :gutter="10">
      <el-col :span="8" :xs="24">
        <el-card style="margin-bottom:20px;">
          <el-tree
            :data="dataTree"
            :props="defaultProps"
            node-key="id"
            highlight-current
            :default-expanded-keys="expandedIds"
            :expand-on-click-node="false"
            :render-content="renderContent"
            @node-click="showBindVideo=false"
          />
        </el-card>
      </el-col>
      <el-col :span="16" :xs="24">
        <el-card style="margin-bottom:20px;">
          <div slot="header" class="clearfix">
            <span>设备信息</span>
          </div>
          <el-form ref="form" :model="form" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备编号">
                  <el-input
                    v-model="form.deviceNumber"
                    :disabled="form.deviceNumberDisable"
                    placeholder="设备编号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备名称">
                  <el-input
                    v-model="form.deviceName"
                    :disabled="form.deviceNameDisable"
                    placeholder="设备名称"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="规格型号">
                  <el-input
                    v-model="form.specificationType"
                    :disabled="form.specificationTypeDisable"
                    placeholder="规格型号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备类型">
                  <el-input v-model="form.deviceTypeFont" :disabled="true" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="设备品牌">
                  <el-input v-model="form.brand" :disabled="form.brandDisable" placeholder="设备品牌" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产厂家">
                  <el-input
                    v-model="form.manufacturer"
                    :disabled="form.manufacturerDisable"
                    placeholder="生产厂家"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="生产日期">
                  <el-input
                    v-model="form.manufactureDate"
                    :disabled="form.manufactureDateDisable"
                    placeholder="生产日期"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item v-if="form.vifratedCapacity" label="额定容量">
                  <el-input
                    v-model="form.ratedCapacity"
                    :disabled="form.ratedCapacityDisable"
                    placeholder="额定容量"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="关联设备">
                  <div class="select-sea" @click.stop>
                    <el-input
                      v-model="seaStr"
                      :disabled="form.ratedCapacityDisable"
                      placeholder="请选择"
                      @input="seaInputChange"
                      @focus="showBindVideo=true;oldAllVideo=JSON.parse(JSON.stringify(allVideo))"
                    />
                    <div v-if="showBindVideo" class="sea-content">
                      <div v-for="(val,index) in allVideo" :key="index">
                        <div
                          v-if="val.filterInput"
                          class="dis-start sea-one"
                          @click="val.check=!val.check"
                        >
                          <input type="checkbox" :checked="val.check">
                          <span>{{ val.deviceName }}</span>
                        </div>
                      </div>
                      <div v-if="allVideo.filter(v=>v.filterInput).length" class="dis-end">
                        <el-button
                          size="mini"
                          type="default"
                          @click="allVideo=oldAllVideo;showBindVideo=false"
                        >取消</el-button>
                        <el-button size="mini" type="primary" @click="relatedSubmit">提交</el-button>
                      </div>
                      <div v-else class="dis-cen">暂无数据</div>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="设备图">
                  <el-input
                    v-model="form.ratedCapacity"
                    :disabled="form.ratedCapacityDisable"
                    placeholder="设备图"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="扩展字段">
                  <JsonEditor ref="extData" :value="form.extData" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="margin-top: 30px;">
              <el-col :span="4" :offset="16">
                <el-button
                  type="default"
                  :disabled="nowFormStatus === 'default' ? true : false"
                  @click="onCancel"
                >取消</el-button>
              </el-col>
              <el-col :span="4" :offset="0">
                <el-button
                  type="primary"
                  :disabled="nowFormStatus === 'default' ? true : false"
                  @click="onSubmit()"
                >提交</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  queryAllByPage,
  update,
  selectCameraByDeviceId,
  bindCamera
} from '@/api/deviceInfo'
import { handleByDeviceType, isJSON } from '@/utils/handle'
import JsonEditor from '@/components/JsonEditor/index'
const form = {
  deviceNumber: '',
  deviceNumberDisable: true,
  deviceName: '',
  deviceNameDisable: true,
  specificationType: '',
  specificationTypeDisable: true,
  brand: '',
  brandDisable: true,
  manufacturer: '',
  manufacturerDisable: true,
  manufactureDate: '',
  manufactureDateDisable: true,
  ratedCapacity: '',
  ratedCapacityDisable: true,
  vifratedCapacity: true,
  deviceTypeFont: '',
  extData: '{}'
}
export default {
  components: {
    JsonEditor
  },
  data() {
    return {
      dataTree: [],
      form: JSON.parse(JSON.stringify(form)),
      // 所有的摄像头设备
      allVideo: [],
      oldAllVideo: [],
      // 显示绑定信息
      showBindVideo: false,
      seaStr: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      nowFormStatus: 'default',
      expandedIds: []
    }
  },
  created() {
    this.loadData()
  },
  mounted() {
    document.addEventListener('click', this.closeBind)
  },
  destroyed() {
    document.removeEventListener('click', this.closeBind)
  },
  methods: {
    closeBind() {
      if (this.showBindVideo) {
        this.showBindVideo = false
        this.allVideo = this.oldAllVideo
      }
    },
    seaInputChange(str) {
      this.allVideo.map(v => {
        v.filterInput = v.deviceName.indexOf(str) != -1
        return v
      })
    },
    // 編輯
    edit(data) {
      this.nowFormStatus = 'update'
      this.form = {
        id: data.id,
        deviceNumber: data.deviceNumber,
        deviceNumberDisable: false,
        deviceName: data.deviceName,
        deviceNameDisable: false,
        specificationType: data.specificationType,
        specificationTypeDisable: false,
        brand: '没有这个字段',
        brandDisable: false,
        manufacturer: data.manufacturer,
        manufacturerDisable: false,
        manufactureDate: data.manufactureDate,
        manufactureDateDisable: false,
        ratedCapacity: data.ratedCapacity,
        ratedCapacityDisable: false,
        vifratedCapacity: true,
        deviceTypeFont: handleByDeviceType(data.deviceType),
        extData: data.extData ? JSON.parse(data.extData) : '{}'
      }
      // 封装关联设备
      const allVideo = this.allVideo.map(v => {
        v.check = false
        v.filterInput = true
        return v
      })
      selectCameraByDeviceId({ deviceId: data.id })
        .then(res => {
          if (res.data && res.data.length) {
            for (const alli in allVideo) {
              for (const havai in res.data) {
                if (allVideo[alli].id == res.data[havai].id) {
                  allVideo[alli].check = true
                  break
                }
              }
            }
          }
          this.allVideo = allVideo
        })
        .catch(error => {
          console.log(error)
          this.allVideo = allVideo
        })
      data.deviceType == 3 && (this.form.vifratedCapacity = false)
    },
    // 定位
    openDevice(data) {
      let component
      switch (data.deviceType) {
        case 1:
          // 油罐
          component = 'OilTankInfo'
          break
        case 2:
          // 加油机
          component = 'TankerInfo'
          break
        case 3:
          // 摄像机
          component = 'CameraInfo'
          break
        case 4:
          // 周界防范电子围栏
          component = 'ElectricFenceInfo'
          break
        case 5:
          // 人车识别一体机
          component = 'VehiclelDentificationInfo'
          break
        case 6:
          // 汽车零发
          component = 'CarZeroInfo'
          break
        default:
          break
      }
      this.$bus.emit('drawerDialog', {
        component: component,
        componentdata: data
      })
    },
    onSubmit(formData) {
      const formParms = this.form
      const params = {}
      let str, item
      for (str in formParms) {
        if (
          str.indexOf('Disable') == -1 &&
          str != 'deviceTypeFont' &&
          str != 'brand' &&
          str != 'vifratedCapacity' &&
          str != 'extData' &&
          formParms[str]
        ) {
          params[str] = formParms[str]
        }
      }
      const extJSONStr = this.$refs.extData.getValue()
      if (isJSON(extJSONStr)) {
        params.extData = extJSONStr
      }
      update(params).then(res => {
        this.$message({
          type: 'success',
          message: `更新成功!`
        })
        this.reset()
      })
    },
    relatedSubmit() {
      bindCamera({
        deviceId: this.form.id,
        cameraIds: this.allVideo
          .filter(v => v.check)
          .map(v => {
            return v.id
          })
      }).then(res => {
        if (res.statusCode == 200) {
          this.$message({
            type: 'success',
            message: `更新关联成功!`
          })
          this.showBindVideo = false
        }
      })
    },
    onCancel() {
      this.form = form
      this.nowFormStatus = 'default'
    },

    renderContent(h, { node, data, store }) {
      return (
        <span style='flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;'>
          <span>
            <span>{data.label}</span>
          </span>
          <span>
            {!data.isMain && (
              <el-button
                style='font-size: 12px; color:#67C23A; margin-left:6px;'
                type='text'
                on-click={() => this.openDevice(data)}
                disabled={false}
              >
                {' '}
                定位
              </el-button>
            )}
            {!data.isMain && (
              <el-button
                style='font-size: 12px;'
                type='text'
                disabled={false}
                on-click={() => this.edit(data)}
              >
                {' '}
                编辑
              </el-button>
            )}
          </span>
        </span>
      )
    },

    reset() {
      this.loadData()
      this.onCancel()
    },

    loadData() {
      const param = { pageNum: -1 }
      queryAllByPage(param)
        .then(res => {
          this.handleTree(res.data)
        })
        .catch(error => {
          console.log(error)
        })
    },

    handleTree(d) {
      const expandedIds = []
      const device = JSON.parse(
        JSON.stringify(this.$store.state.device.device_type)
      ).map((val, index) => {
        const deviceTypeId = val.id
        val.deviceTypeId = deviceTypeId
        val.label = val.enumCvalue
        val.id = 1000000 + index
        val.children = []
        val.isMain = true
        expandedIds.push(val.id)
        return val
      })
      for (const i in d) {
        for (const devi in device) {
          if (d[i].deviceType == device[devi].deviceTypeId) {
            d[i].children = []
            d[i].label = d[i].deviceName
            device[devi].children.push(d[i])
            break
          }
        }
      }
      this.allVideo = d
        .filter(v => v.deviceType == 3)
        .map(v => {
          v.filterInput = true
          return v
        })
      this.dataTree = device
      //   this.expandedIds = expandedIds
    }
  }
}
</script>

<style lang="scss" rel="stylesheet/scss" scoped>
$color-blue: #2196f3;
$space-width: 18px;
@import "~@/styles/variables.scss";
@import "~@/styles/com.scss";

.permissions-wrap {
  padding: 10px 0;
  overflow-x: hidden;
}

.tree-ctrl {
  cursor: pointer;
}

.ms-tree-space {
  position: relative;
  top: 1px;
  display: inline-block;
  font-style: normal;
  font-weight: 400;
  line-height: 1;
  width: $space-width;
  height: 14px;
  &::before {
    content: "";
  }
}

.processContainer {
  width: 100%;
  height: 100%;
}

table td {
  line-height: 26px;
}

.tree-ctrl {
  position: relative;
  cursor: pointer;
  color: $color-blue;
  margin-left: -$space-width;
}

.select-sea {
  position: relative;
}
.sea-content {
  margin-top: 5px;
  padding: 6px;
  border: 1px solid rgb(230, 162, 60);
  border-radius: 4px;
  .sea-one {
    span {
      padding-left: 10px;
    }
  }
}
input[type="checkbox"] {
  -webkit-appearance: none; //这个属性是将input标签变成一个可修改样式的普通标签，目前有谷歌和火狐浏览器支持
  -moz-appearance: none;
  width: 16px;
  border-radius: 2px;
  height: 16px;
  background-color: transparent;
  border: 1px solid #fff;
  color: transparent;
  outline: none;
}

input[type="checkbox"]:checked::after {
  content: "\2713";
  color: #fff;
}
</style>
